package com.project.eric.Http;

import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EncodingUtils;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * <h3>Description</h3>
 * TODO
 * <h3>Author</h3> luzhenbang
 * <h3>Date</h3> 2018/1/18 15:01
 * <h3>Copyright</h3> Copyright (c)2018 Shenzhen TL  Co., Ltd. Inc. All rights reserved.
 */
public class HttpUtils {

    private HttpURLConnection urlConnection;
    private String result;
    private static HttpUtils httpUtils;

    private HttpUtils() {
    }

    public static HttpUtils getInstance() {
        if (null == httpUtils){
            httpUtils = new HttpUtils();
        }
        return httpUtils;
    }


    public void get(String url, RequestCallBack callBack){
        try {
            URL path  = new URL(url);
            urlConnection = (HttpURLConnection) path.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("Cache-Control","no-cache");
            //表示接受数据的类型 如果可以接受的序列化的java对象，添加类型application/x-www-form-urlencoded
//            connection.setRequestProperty("Accept","image/gif, image/jpeg, image/pjpeg, image/pjpeg, " +
//                    "application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, " +
//                    "application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, " +
//                    "application/vnd.ms-powerpoint, application/msword,text/xml , text/html ,application/json ,*/*");
            urlConnection.setRequestProperty("Accept-Language","zh-cn");
            urlConnection.setConnectTimeout(5000);
            urlConnection.setReadTimeout(5000);
            urlConnection.connect();
            int code = urlConnection.getResponseCode();
            if (code == HttpURLConnection.HTTP_OK){
                BufferedInputStream bis = new BufferedInputStream(urlConnection.getInputStream());
                ByteArrayBuffer arrayBuffer = new ByteArrayBuffer(1024);
                int length = -1;
                while ((length = bis.read()) != -1) {
                    arrayBuffer.append(length);
                }
                result = EncodingUtils.getString(arrayBuffer.toByteArray(),"utf-8");
                if (null != callBack){
                    callBack.onCall(result,null);
                }
                bis.close();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
            if (null != callBack){
                callBack.onCall(result,e);
            }
        } catch (IOException e) {
            e.printStackTrace();
            if (null != callBack){
                callBack.onCall(result,e);
            }
        }
    }

}
